var demo;
//当前结点的key值
var nodeId;
var mark = 0;
var viewPageId;
var versionNote;
var newJson;
//已有的流程图所有节点属性的数据
var properties={};
//已有的流程图数据
var json =null;
//判断流程是否有数据
if(processJson!=null&&processJson!="null"){
	json =JSON.parse(processJson);
	//取出已有的流程图所有节点属性的数据
	properties = json["properties"];
}
var property = {
	width: 1000,
	height: 500,
	toolBtns: ["start round", "end round", "userTask", "multiTaskOr","examine"],//   , "complex mix , "chat", "state", "plug", "join", "fork""
	haveHead: false,
	headBtns: ["new", "open", "save", "undo", "redo", "reload"], //如果haveHead=true，则定义HEAD区的按钮
	haveTool: true,
	haveGroup: true,
	useOperStack: true
};
var remark = {
	cursor: "选择指针",
	direct: "结点连线",
	start: "开始节点",
	end: "结束结点",
	userTask: "单任务结点",
	multiTaskOr: "多任务节点",
	examine:"审批节点",
	group: "组织划分框编辑开关"
};
/*重新加载流程图*/
function reLoadFolw(nextNodeIds){
    var newJson = demo.exportData(properties);
    var i=0;
    /*判断该节点的所有连线，并清除*/
    for(var lineKey in newJson.lines){
    	var index = lineKey.lastIndexOf("_");
    	var linePrefix = lineKey.substring(0,index);
    	if(linePrefix == nodeId+"_line"){
    		i+=1;
    		newJson.lines[nodeId+"_line_"+i] = null;
    	}
    }
    /*重新画该节点的线*/
    for(var j=0;j<nextNodeIds.length;j++){
    	var line = {type:"sl",from:nodeId,to:nextNodeIds[j],name:"",alt:true};
    	newJson.lines[nodeId+"_line_"+(j+1)]=line;
    }
    demo.destrory();
    demo = $.createGooFlow($("#demo"), property);
    demo.setNodeRemarks(remark);
    demo.loadData(newJson);
}

/**
 * 右键属性事件
 **/
function pptFun(){
	$("#daiLog").show();
	if(json !=null){
		properties= json['properties'];
		sessionStorage.setItem("properties",JSON.stringify(properties));
	}
	//获取所有的节点
	var nodeStr =demo.$nodeData;
	sessionStorage.setItem("nodeStr",JSON.stringify(nodeStr));
	var currentNodeName = nodeStr[nodeId].name;
	$("#rightMenu").remove();
	//单任务节点
	if(nodeStr[nodeId].type == "userTask"){
		sessionStorage.setItem("userTaskJson",JSON.stringify(properties[nodeId]));
		if(json == null){
			sessionStorage.setItem("userTaskJson",null);
		}
		$.ligerDialog.open({title: currentNodeName, width: 725,height:600, allowClose: false, url: path + '/flow/userTaskNode?currentNodeId='+nodeId+'&processId='+processId,
			buttons: [{ text: '确定', onclick: function (item, dialog) {
				var nodeJson = dialog.frame.createJson();
					if(dialog.frame.fkId() ==""){
						alert("流程执行人不能为空");
						return;
					}
					if(dialog.frame.isNoticesNull){
						properties[nodeId] = nodeJson;
						var nextNodeIds = dialog.frame.nextNodeId();
						dialog.close();
						reLoadFolw(nextNodeIds);
						json = demo.exportData(properties);
					}
				}
			},
	        { text: '关闭', onclick: function (item, dialog) {
	        	dialog.close();
	        	}
	        }]
		});
	//审批节点
	}else if(nodeStr[nodeId].type == "examine"){
	    sessionStorage.setItem("examineJson",JSON.stringify(properties[nodeId]));
	    if(json == null){
	    	sessionStorage.setItem("examineJson",null);
	    }
	    $.ligerDialog.open({title: currentNodeName, width: 635,height:550, allowClose: false, url:path + '/flow/examineNode?currentNodeId='+nodeId+'&processId='+processId,
	    	buttons: [
				{ text: '确定', onclick: function (item, dialog) {
					var nodeJson = dialog.frame.createJson();
					if(dialog.frame.fkId() ==""){
						$.ligerDialog.warn("流程执行人不能为空");
						return;
					}
					if(dialog.frame.isNoticesNull){
						properties[nodeId] = nodeJson;
						var nextNodeId = dialog.frame.nextNodeId();
						dialog.close();
						reLoadFolw(nextNodeId);
						json = demo.exportData(properties);
					}
				}},
				{ text: '关闭', onclick: function (item, dialog) {
					dialog.close();
				}}
			]
	    });
	//多任务节点
	}else if(nodeStr[nodeId].type == "multiTaskOr"){
		if(properties[nodeId] != undefined){
			sessionStorage.setItem("childNode",JSON.stringify(properties[nodeId].tasks));
		}
		if(json == null){
			sessionStorage.setItem("childNode","");
		}
		sessionStorage.setItem("currentNodeId",nodeId);
		$.ligerDialog.open({title: currentNodeName, width: 635,height:550, allowClose: false, url: path + '/flow/multiTaskOr?currentNodeId='+nodeId+'&processId='+processId,
			buttons: [
				{ text: '确定', onclick: function (item, dialog) {
					var nodeJson = dialog.frame.createJson();
					properties[nodeId] = nodeJson;
					var nextNodes = dialog.frame.getAllChildNodeId();
					dialog.close();
					reLoadFolw(nextNodes);
					json = demo.exportData(properties);
				}},
				{ text: '关闭', onclick: function (item, dialog) {
					dialog.close();
				}}
			]
		});
	
	/*开始节点*/
	}else if(nodeStr[nodeId].type == "start round"){
		$.ligerDialog.open({title: "开始", width: 320,height:170, allowClose: false, url: path + '/flow/startNode?currentNodeId='+nodeId,
			buttons: [
			{ text: '确定', onclick: function (item, dialog) {
				var nextNodeIds = dialog.frame.nextNodeId();
				dialog.close();
				reLoadFolw(nextNodeIds);
				json = demo.exportData(properties);
			}},
			{ text: '关闭', onclick: function (item, dialog) {
				dialog.close();
			}}
			]
		});
	}

}

/*保存方法*/
function save(isNewVersion,title){
	$.ligerDialog.open({title: title, width: 330,height:350, allowClose: false, url: path+'/flow/process/flowSaveDialog?processId='+processId+'&isNewVersion='+isNewVersion,
		buttons: [
			{ text: '确定', onclick: function (item, dialog) {
				var msg = dialog.frame.getMsg();
				viewPageId = msg.viewPageId;
				versionNote = msg.versionNote;
				newJson = demo.exportData(properties);
				newJson["title"] = '${processName}';
				/*判断： 把没有值的属性删除*/
				for(var k in newJson){
					if(JSON.stringify(newJson[k])==undefined || JSON.stringify(newJson[k]) == "" || JSON.stringify(newJson[k]) == null ||JSON.stringify(newJson[k]) == "{}"){
						delete newJson[k];
					}
				}
				var newJsonStr = JSON.stringify(newJson);
				if(viewPageId==""){
					$.ligerDialog.warn("请选择显示页面！");
					return;
				}
				if(versionNote == ""){
					$.ligerDialog.warn("请填写版本说明！");
					return;
				}
				$.ligerDialog.waitting('正在保存中,请稍候...')
				$.ajax({
				url:'${_ctx}/flow/process/set/json?isNewVersion='+isNewVersion,
				type:'post',
				dataType:'json',
				data:{processId:'${processId}',versionNote:versionNote,viewPageId:viewPageId,json:newJsonStr.replace(/\\n/g,"")},
				success:function(responseText){
					$.ligerDialog.closeWaitting();
					if (!responseText.isError) {
						$.ligerDialog.success("保存成功！");
						if(mark == 0){
							mark = 1;
						}
					} else {
						$.ligerDialog.warn('保存失败！');
					}
				},
				error: function () {
					$.ligerDialog.closeWaitting();
					$.ligerDialog.error('系统错误！');
				}
				});
				dialog.close();
			}},
			{ text: '关闭', onclick: function (item, dialog) {
				dialog.close();
			}}
		]
	});
}


$(function(){
	$("#daiLog").width($(window).width()-2);
    $("#daiLog").height($(window).height()-2);
    $("#daiLog").width($(window).width()-2);
    $("#daiLog").height($(window).height()-2);
    $("#demo_node_2").css("background","red");
    //初始化流程图界面
    demo = $.createGooFlow($("#demo"), property);
    /*绑定左侧节点的提示文字*/
    demo.setNodeRemarks(remark);
    if(json != "" && json != null){
    	demo.loadData(json);
	}
    
    /*关闭右键*/
	$("body").click(function(){
		$("#rightMenu").remove();
	});
	
	/*节点的右键*/
	$("#demo").contextmenu(function(event){
		nodeId=null;
		event = event ? event : window.event;
		var obj = event.srcElement ? event.srcElement : event.target;
		var $obj = $(obj);
		$("#rightMenu").remove();
		var x = event.pageX;
		var y = event.pageY;
		//获取所有的节点
		var nodeStr =demo.$nodeData;
		if($obj.is("i")){
			nodeId = $obj.parent().parent().parent().parent().parent().attr('id');
		}else if($obj.is('td')){
			nodeId = $obj.parent().parent().parent().parent().attr('id');
		}
		if(!nodeStr[nodeId]){
			return;
		}
		if(nodeStr[nodeId].type != "end round"){
			var menu = "<ul id='rightMenu' style='list-style:none;border:1px solid #ccc;"+
			"font-size:12px;text-align:center;line-height: 20px;width:80px;"+
			"position:absolute;background:#BEE1F6;z-index:100;top:"+y+"px;left:"+x+"px;"+
			"border-radius:3px'>"+
			"<li id='property' onclick='pptFun()'style='cursor:pointer'>属  性</li>"+
			"</ul>";
			$("body").append(menu);
		}
	});
	
	/*保存流程图*/
	$("#save").click(function(){
		newJson = demo.exportData(properties);
		newJson["title"] = '${processName}';
		/*判断： 把没有值的属性删除*/
		for(var k in newJson){
			if(newJson[k]==undefined || newJson[k] == "" || newJson[k] == null ||newJson[k] == {} ||  newJson[k] == {}){
				delete newJson[k];
			}
		}
		var newJsonStr = JSON.stringify(newJson);
		$.ajax({
			url:path+'/flow/process/set/json?isNewVersion=0',
			type:'post',
			dataType:'json',
			data:{"processId":processId,json:newJsonStr.replace(/\\n/g,"")},
			success:function(responseText){
				if (!responseText.isError) {
					alert("保存成功！");
				} else {
					alert(responseText.message);
				}
			},
			error: function () {
				alert('系统错误！');
			}
		});
	});
	
	/*另存流程图为新版本*/
	$("#newSave").click(function(){
		save('1','另存为新版本');
	});
	
	/*清除*/
	$("#clear").click(function(){
		demo.destrory();
		demo = $.createGooFlow($('#demo'), property);
		demo.setNodeRemarks(remark);
		json = null;
		processJson = null;
		properties = {}
		sessionStorage.clear();
		mark = 0;
	});
});